package HTTP;

/**
 * Created by 蜡笔小新丶 on 2017/6/6.
 */

import Arithmetic4.ED2.MyBC;

import java.io.*;

import java.net.*;
import java.util.ArrayList;


public class SocketDemo1 {
    public static void main(String args[]) {
        Socket socket = null;
        ArrayList<String> list = new ArrayList<String>();
        MyBC ori = new MyBC();
        try {
            try {
                 socket = new Socket("127.0.0.1", 9005);
                 System.out.println("连接成功！");
            }catch (Exception e){
                System.out.println("服务器连接异常！");
                System.out.println(e);
            }
            System.out.println("当用户输入OK则停止！"+ "\n输入“File”发送文件");
            //向本机的4700端口发出客户请求
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            //由系统标准输入设备构造BufferedReader对象
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            //由Socket对象得到输出流，并构造PrintWriter对象
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //由Socket对象得到输入流，并构造相应的BufferedReader对象
            String readline;
            readline = sin.readLine(); //从系统标准输入读入一字符串
            while (!readline.equals("OK")) {
                if (readline.equals("File")) {
                    os.println(readline);
                    os.flush();
                    readline = sin.readLine();
                    BufferedReader br = new BufferedReader(new FileReader(readline));
                    while (readline!=null) {
                        readline = br.readLine();
                        list.add(readline);
                    }
                    br.close();
                    os.println(list);
                    os.flush();
                    readline = sin.readLine();
                } else {
                    ori.evaluate(readline);
                    String A = ori.getMessage();
                    //若从标准输入读入的字符串为 "OK"则停止循环
                    os.println(A);
                    //将从系统标准输入读入的字符串输出到Server
                    os.flush();
                    //刷新输出流，使Server马上收到该字符串
                    System.out.println("客户端发送:" + A);
                    //在系统标准输出上打印读入的字符串
                    System.out.println("客户端接收:" + is.readLine());
                    //从Server读入一字符串，并打印到标准输出上
                    readline = sin.readLine(); //从系统标准输入读入一字符串
                } //继续循环
            }
            os.close(); //关闭Socket输出流
            is.close(); //关闭Socket输入流
            socket.close(); //关闭Socket
        } catch (Exception e) {
            System.out.println("Error" + e); //出错，则打印出错信息
        }
    }
}
